// pages/sharePicture/sharePicture.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    Width: 0,
    Height: 0,
    userInfo: {},
    imagePath: '/images/background.png',
    openSet: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.draw()
  },
  /**
   * 画布绘制
   */
  draw: function (e) {
    var that = this
    //获取系统信息及画布信息
    wx.getSystemInfo({
      success: res => {
        console.log(res);
        that.setData({
          Width: res.screenWidth,
          Height: res.screenHeight,
          userInfo: app.globalData.userInfo
        })
        console.log(that.data.Width)
        console.log(that.data.userInfo)
      }
    })
    var qrcode = '/images/code.png' //二维码图片一般为网络图片后台生成
    var logoImgPath = '/images/miniImg.png' //logo图
    var avatar = that.data.userInfo.avatarUrl //头像的图片
    var pichName = that.data.userInfo.nickName //昵称
    var bgImgPath = '/images/background.png' //背景图
    var statusImgPath = '/images/photo.png' //效果图
    var width = that.data.Width //封面图宽
    var height = that.data.Height //封面图高

    const ctx = wx.createCanvasContext('myCanvas') //创建 canvas 绘图上下文
    const date = new Date;
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const name = "抽奖小助手"
    const day = date.getDate();
    const time = year + '.' + month + '.' + day; // 绘图的时间
    const explain = 'Hi,我想分享给你一个抽奖程序!';

    //绘制logo
    ctx.save()
    //背景图
    ctx.drawImage(bgImgPath, 0, 0, 300, 480);
    //绘制logo
    ctx.drawImage(logoImgPath, 140, 25, 128, 34);
    ctx.drawImage(statusImgPath, 16, 90, 260, 180);
    //绘制时间
    ctx.setFontSize(12);
    ctx.setTextAlign('right');
    const metrics = ctx.measureText(time).width; //时间文字的所占宽度
    ctx.fillText(time, 266, 78, metrics + 5);
    //绘制标题
    ctx.font = 'normal bold 14px sans-serif';
    ctx.setTextAlign('left');
    const nameWidth = ctx.measureText(name).width;
    //标题换行处理
    this.wordsWrap(ctx, name, nameWidth, 252, 16, 252, 16);
    // 计算标题所占高度
    const titleHight = Math.ceil(nameWidth / 252) * 16;
    // 绘制头像和昵称
    ctx.arc(36, 268 + titleHight, 20, 0, 2 * Math.PI);
    ctx.clip()
    ctx.drawImage(avatar, 16, 248 + titleHight, 40, 44);
    ctx.restore();
    ctx.font = 'normal normal 14px sans-serif';
    ctx.setTextAlign('left');
    ctx.setFillStyle('#bbbbbb');
    ctx.fillText(pichName, 70, 270 + titleHight);
    // 二维码描述 及图片
    ctx.setStrokeStyle('#eeeeee');
    ctx.strokeRect(16, 300 + titleHight, 252, 80);
    ctx.setFillStyle('#333333')
    ctx.fillText(explain.slice(0, 11), 30, 336 + titleHight); // 描述截取换行
    ctx.fillText(explain.slice(11), 30, 358 + titleHight);
    ctx.drawImage(qrcode, 194, 308 + titleHight, 44, 44);
    ctx.setFontSize(10);
    ctx.setFillStyle('#bbbbbb')
    ctx.fillText('长按扫码查看详情', 175, 370 + titleHight);
    //绘图
    ctx.draw()

    //canvas画图需要时间而且还是异步的，所以加了个定时器
    //将生成的canvas图片，转为真实图片
    setTimeout(() => {
      // 将生成的canvas图片，转为真实图片
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        canvasId: 'myCanvas',
        success: function (res) {
          let shareImg = res.tempFilePath;
          that.setData({
            imagePath: shareImg
          })
        },
        fail: function (res) {
          console.log(res)
        }
      })
    }, 500)
  },
  //文字换行处理
  // canvas 标题超出换行处理
  wordsWrap(ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
    let lineWidth = 0;
    let lastSubStrIndex = 0;
    for (let i = 0; i < name.length; i++) {
      lineWidth += ctx.measureText(name[i]).width;
      if (lineWidth > maxWidth) {
        ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY);
        srartY += wordsHight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i == name.length - 1) {
        ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY);
      }
    }
  },
  /**
   * 保存图片
   */
  save: function (e) {
    var that = this
    // 获取用户是否开启用户授权相册
    wx.getSetting({
      success: function (res) {
        // 如果没有则获取授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: that.data.imagePath,
                success() {
                  wx.showToast({
                    title: '保存成功'
                  })
                },
                fail() {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none'
                  })
                }
              })
            },
            fail() {
              // 如果用户拒绝过或没有授权，则再次打开授权窗口
              that.setData({
                openSet: true
              })
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: that.data.imagePath,
            success() {
              wx.showToast({
                title: '保存成功'
              })
            },
            fail() {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  // 授权
  cancleSet() {
    this.setData({
      openSet: false
    })
  },
})